//
//  DataSummaryLocationCell.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/24.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import CoreLocation

class DataSummaryLocationCell: DataSummaryCell {
    
    @IBOutlet var longitudeLabel: UILabel!
    @IBOutlet var latitudeLabel: UILabel!
    @IBOutlet var altitudeLabel: UILabel!
    
    private var location: CLLocation?
    
    override func willMove(toWindow newWindow: UIWindow?) {
        if newWindow == nil {
            LocManager.shared.stop()
        } else {
            LocManager.shared.start { [weak self] loc in
                self?.update(locaton: loc)
            }
        }
    }
    
    func update(locaton: CLLocation?) {
        let corr = locaton?.coordinate
        longitudeLabel.text = "东经 " + (corr?.longitudeDes ?? "--")
        latitudeLabel.text = "北纬 " + (corr?.latitudeDes ?? "--")
        altitudeLabel.text = "海拔 " + (locaton?.altitude.int.string ?? "--")
    }
}

fileprivate extension CLLocationDegrees {
    func toStr() -> String {
        return String.init(format: "%.2f", self)
    }
}

fileprivate extension CLLocationCoordinate2D {
    var latitudeDes: String { return latitude.toStr() }
    var longitudeDes: String { return longitude.toStr() }
}

fileprivate class LocManager: NSObject, CLLocationManagerDelegate {
    
    static let shared = LocManager()
    
    lazy var clm: CLLocationManager = {
        let ins = CLLocationManager()
        if CLLocationManager.locationServicesEnabled() {
            ins.delegate = self
            ins.activityType = .fitness
            ins.desiredAccuracy = kCLLocationAccuracyBest
            ins.distanceFilter = 5
            ins.requestWhenInUseAuthorization()
        }
        return ins
    }()
    
    private var completion: ((CLLocation?) -> Void)?
    
    func start(completion: @escaping (CLLocation?) -> Void) {
        self.completion = completion
        if let old = clm.location {
            completion(old)
        }
        if isAuthorized {
            clm.startUpdatingLocation()
        }
    }
    
    func stop() {
        clm.stopUpdatingLocation()
        completion = nil
    }
    
    var isAuthorized: Bool {
        let status: CLAuthorizationStatus = {
            if #available(iOS 14, *) {
                return clm.authorizationStatus
            }
            return CLLocationManager.authorizationStatus()
        }()
        return status == .authorizedAlways || status == .authorizedWhenInUse
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        completion?(locations.first)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        completion?(nil)
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if let c = completion {
            start(completion: c)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if let c = completion {
            start(completion: c)
        }
    }
}
